from fastapi import APIRouter, HTTPException
from typing import List
from pydantic import BaseModel
from utils import attendance_types_curd
import sqlite3

router = APIRouter(
    tags=["attendance-types"]
)

class AttendanceTypeBase(BaseModel):
    type_id: int
    type_name: str

class AttendanceTypeCreate(AttendanceTypeBase):
    pass

class AttendanceType(AttendanceTypeBase):
    class Config:
        from_attributes = True

@router.get("/", response_model=List[AttendanceType])
async def get_attendance_types():
    """获取所有考勤类型"""
    return attendance_types_curd.get_all_attendance_types()

@router.get("/{type_id}", response_model=AttendanceType)
async def get_attendance_type(type_id: int):
    """获取指定考勤类型"""
    attendance_type = attendance_types_curd.get_attendance_type(type_id)
    if not attendance_type:
        raise HTTPException(status_code=404, detail="Attendance type not found")
    return attendance_type

@router.post("/", response_model=AttendanceType)
async def create_attendance_type(attendance_type: AttendanceTypeCreate):
    """创建新考勤类型"""
    try:
        return attendance_types_curd.create_attendance_type(attendance_type.dict())
    except sqlite3.IntegrityError:
        raise HTTPException(status_code=400, detail="Attendance type ID already exists")

@router.put("/{type_id}", response_model=AttendanceType)
async def update_attendance_type(type_id: int, attendance_type: AttendanceTypeCreate):
    """更新考勤类型"""
    updated_type = attendance_types_curd.update_attendance_type(type_id, attendance_type.dict())
    if not updated_type:
        raise HTTPException(status_code=404, detail="Attendance type not found")
    return updated_type

@router.post("/batch", response_model=List[AttendanceType])
async def batch_create_attendance_types(types: List[AttendanceTypeCreate]):
    """批量创建考勤类型"""
    try:
        return attendance_types_curd.batch_create_attendance_types([type_data.dict() for type_data in types])
    except sqlite3.IntegrityError:
        raise HTTPException(status_code=400, detail="One or more attendance type IDs already exist")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")